package cn.itcast.service.impl;

import cn.itcast.service.ChatService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

/**
 * @author wys
 * @version V1.0
 * @date 2025-04-20 10:14
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class ChatServiceImpl implements ChatService {

    private final ChatClient chatClient;

    private final VectorStore vectorStore;

    /**
     * 流式聊天
     *
     * @param question  用户提问
     * @param sessionId 对话id
     * @return 大模型的回答
     */
    @Override
    public Flux<String> chatStream(String question, String sessionId) {
        SearchRequest searchRequest = SearchRequest.builder()
                .query(question) // 设置查询条件
                .topK(1) // 设置最多返回的文档数量
                .build();
        return chatClient.prompt()
                .advisors(advisorSpec -> advisorSpec
                        .advisors(new QuestionAnswerAdvisor(vectorStore, searchRequest))
                        .param(AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY, sessionId))
                .user(question)
                .stream()
                .content()
                .concatWith(Flux.just("[END]"));
    }
}
